import { Map } from "../../Map";
import { MapRenderer } from "../Map";
export class CanvasMapRenderer extends MapRenderer {
  private context_: CanvasRenderingContext2D;
  private canvas_: HTMLCanvasElement;
  private layerRendererConstructors: Array<any> = [];

  constructor(map: Map) {
    super(map);
    const container = map.getViewport();

    this.context_ = this.createCanvasContext2D();
    this.canvas_ = this.context_.canvas;
    this.canvas_.style.width = "100%";
    this.canvas_.style.height = "100%";
    this.canvas_.style.display = "block";
    //   this.canvas_.className = CLASS_UNSELECTABLE;
    container.insertBefore(this.canvas_, container.childNodes[0] || null);
  }

  /**
   * Create an html canvas element and returns its 2d context.
   * @param {number=} opt_width Canvas width.
   * @param {number=} opt_height Canvas height.
   * @return {CanvasRenderingContext2D} The context.
   */
  public createCanvasContext2D(opt_width?: number, opt_height?: number) {
    let canvas: HTMLCanvasElement = document.createElement("canvas");
    if (opt_width) {
      canvas.width = opt_width;
    }
    if (opt_height) {
      canvas.height = opt_height;
    }
    return canvas.getContext("2d");
  }

  public renderFrame(frameState) {
    const context = this.context_;
    const layerStatesArray = frameState.layerStatesArray;
    const viewResolution = frameState.viewState.resolution;

    let i, ii, layer, layerRenderer, layerState;
    for (i = 0, ii = layerStatesArray.length; i < ii; ++i) {
      layerState = layerStatesArray[i];
      layer = layerState.layer;
      layerRenderer = /** @type {module:ol/renderer/canvas/Layer} */ this.getLayerRenderer(
        layer
      );
      if (layerRenderer.prepareFrame(frameState, layerState)) {
        layerRenderer.composeFrame(frameState, layerState, context);
      }
    }
  }

  public registerLayerRenderers(constructors) {
    MapRenderer.prototype.registerLayerRenderers.call(this, constructors);
    for (let i = 0, ii = constructors.length; i < ii; ++i) {
      const ctor = constructors[i];
      if (this.layerRendererConstructors.indexOf(ctor) !== -1) {
        this.layerRendererConstructors.push(ctor);
      }
    }
  }
}
